package dry.example.iot;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.util.HashMap;

/**
 * 一定要先创建好MNS主题再执行，否则createRuleActionRequest会失败
 * 配置 自己的 公司的
 * MNS_UID 1171406 50137193
 *
 * @author zc
 */
public class Tool {

    private static final String ACCESS_KEY_ID = "";

    private static final String ACCESS_KEY_SECRET = "";

    private static final String END_POINT = "iot.cn-shanghai.aliyuncs.com";

    private static final String MNS_UID = "50137193";

    private static final String MNS_REGION_NAME = "cn-hangzhou";

    private static final String ENV_NAME = "cluster";

    private static final String TOPIC_ONLINE_CALLBACK = ENV_NAME + "-online-callback";

    private static final String TOPIC_ALL = ENV_NAME + "-all";

    private static Client getClient() {
        Config config = new Config();
        config.setAccessKeyId(ACCESS_KEY_ID);
        config.setAccessKeySecret(ACCESS_KEY_SECRET);
        config.setEndpoint(END_POINT);
        try {
            return new Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static CreateProductResponse createProduct(String productName, String description, Integer nodeType, int iotVersion) {
        try {
            Client c = getClient();
            if (c == null) {
                System.out.println("getClient()返回null");
                return null;
            }
            CreateProductRequest r = new CreateProductRequest();
            r.setProductName(productName);
            r.setDescription(description);
            r.setNodeType(nodeType);
            //topic带user，电梯和门禁是0
            if (iotVersion == 1) {
                r.setAliyunCommodityCode("iothub_senior");
                r.setDataFormat(1);
            }
            RuntimeOptions runtime = new RuntimeOptions();
            return c.createProductWithOptions(r, runtime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建产品主题
     *
     * @param productKey     产品key
     * @param topicShortName 主题
     * @param operation      PUB=发布 SUB=订阅 ALL=发布和订阅
     */
    public static CreateProductTopicResponse createProductTopic(String productKey, String topicShortName, String operation) {
        try {
            Client c = getClient();
            if (c == null) {
                System.out.println("getClient()返回null");
                return null;
            }
            CreateProductTopicRequest r = new CreateProductTopicRequest();
            r.setProductKey(productKey);
            r.setTopicShortName(topicShortName);
            r.setOperation(operation);
            RuntimeOptions runtime = new RuntimeOptions();
            return c.createProductTopicWithOptions(r, runtime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static CreateRuleResponse createRuleRequest(String productKey, String name, String desc, String select, String shortTopic, Integer topicType) {
        try {
            Client c = getClient();
            if (c == null) {
                System.out.println("getClient()返回null");
                return null;
            }
            CreateRuleRequest r = new CreateRuleRequest();
            r.setProductKey(productKey);
            r.setName(name);
            r.setRuleDesc(desc);
            r.setDataType("JSON");
            r.setSelect(select);
            r.setShortTopic(shortTopic);
            r.setTopicType(topicType);
            RuntimeOptions runtime = new RuntimeOptions();
            CreateRuleResponse response = c.createRuleWithOptions(r, runtime);
            System.out.println(response.getBody().getErrorMessage());
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static CreateRuleActionResponse createRuleActionRequest(Long ruleId, String configuration) {
        try {
            Client c = getClient();
            if (c == null) {
                System.out.println("getClient()返回null");
                return null;
            }
            CreateRuleActionRequest r = new CreateRuleActionRequest();
            r.setRuleId(ruleId);
            r.setType("MNS");
            r.setConfiguration(configuration);
            RuntimeOptions runtime = new RuntimeOptions();
            return c.createRuleActionWithOptions(r, runtime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static StartRuleResponse startRuleRequest(Long ruleId) {
        try {
            Client c = getClient();
            if (c == null) {
                System.out.println("getClient()返回null");
                return null;
            }
            StartRuleRequest r = new StartRuleRequest();
            r.setRuleId(ruleId);
            RuntimeOptions runtime = new RuntimeOptions();
            return c.startRuleWithOptions(r, runtime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String makeConfiguration(String regionName, String uid, String themeName) {
        HashMap<String, Object> role = new HashMap<>(16);
        role.put("roleArn", String.format("acs:ram::%s:role/aliyuniotaccessingmnsrole", uid));
        role.put("roleName", "AliyunIOTAccessingMNSRole");
        //
        HashMap<String, Object> result = new HashMap<>(16);
        result.put("endPoint", String.format("http://%s.mns.%s.aliyuncs.com/", uid, regionName));
        result.put("regionName", regionName);
        result.put("role", role);
        result.put("themeName", themeName);
        result.put("uid", uid);
        return JSONObject.toJSONString(result);
    }

    public static void ydt() {
        CreateProductResponse response = createProduct(ENV_NAME + "云电梯", "统一创建", 0, 0);
        if (response != null && response.getBody().getProductKey() != null) {
            String productKey = response.getBody().getProductKey();
            //
            createProductTopic(productKey, "handleResult", "PUB");
            createProductTopic(productKey, "cmd", "SUB");
            createProductTopic(productKey, "deviceState", "PUB");
            createProductTopic(productKey, "deviceReportCtrl", "SUB");
            createProductTopic(productKey, "deviceCtrl", "SUB");
            //
            CreateRuleResponse createRuleResponse;
            Long ruleId;
            //
            createRuleResponse = createRuleRequest(productKey, ENV_NAME + "云电梯在线状态回调", "统一创建", "deviceName,status,productKey,time", "+", 2);
            ruleId = createRuleResponse.getBody().getRuleId();
            createRuleActionRequest(ruleId, makeConfiguration(MNS_REGION_NAME, MNS_UID, TOPIC_ONLINE_CALLBACK));
            startRuleRequest(ruleId);
            //
            createRuleResponse = createRuleRequest(productKey, ENV_NAME + "云电梯楼层状态上报", "统一创建", "deviceName() as deviceName,*", "+/deviceState", 1);
            ruleId = createRuleResponse.getBody().getRuleId();
            createRuleActionRequest(ruleId, makeConfiguration(MNS_REGION_NAME, MNS_UID, TOPIC_ALL));
            startRuleRequest(ruleId);
            //
            createRuleResponse = createRuleRequest(productKey, ENV_NAME + "云电梯执行结果上报", "统一创建", "deviceName() as deviceName,*", "+/handleResult", 1);
            ruleId = createRuleResponse.getBody().getRuleId();
            createRuleActionRequest(ruleId, makeConfiguration(MNS_REGION_NAME, MNS_UID, TOPIC_ALL));
            startRuleRequest(ruleId);
        }
    }

    public static void ymj() {
        CreateProductResponse response = createProduct(ENV_NAME + "云门禁", "统一创建", 0, 0);
        if (response != null && response.getBody().getProductKey() != null) {
            String productKey = response.getBody().getProductKey();
            //
            createProductTopic(productKey, "cmd", "SUB");
            createProductTopic(productKey, "deviceState", "PUB");
            //
            CreateRuleResponse createRuleResponse;
            Long ruleId;
            //
            createRuleResponse = createRuleRequest(productKey, ENV_NAME + "云门禁在线状态回调", "统一创建", "deviceName,status,productKey,time", "+", 2);
            ruleId = createRuleResponse.getBody().getRuleId();
            createRuleActionRequest(ruleId, makeConfiguration(MNS_REGION_NAME, MNS_UID, TOPIC_ONLINE_CALLBACK));
            startRuleRequest(ruleId);
            //
            createRuleResponse = createRuleRequest(productKey, ENV_NAME + "云门禁开门状态上报", "统一创建", "deviceName() as deviceName,*", "+/deviceState", 1);
            ruleId = createRuleResponse.getBody().getRuleId();
            createRuleActionRequest(ruleId, makeConfiguration(MNS_REGION_NAME, MNS_UID, TOPIC_ALL));
            startRuleRequest(ruleId);
        }
    }

    public static void ydj() {
        CreateProductResponse response = createProduct(ENV_NAME + "云对讲", "统一创建", 0, 1);
        if (response != null && response.getBody().getProductKey() != null) {
            String productKey = response.getBody().getProductKey();
            //
            createProductTopic(productKey, "cmd", "SUB");
            createProductTopic(productKey, "deviceState", "PUB");
            //
            CreateRuleResponse createRuleResponse;
            Long ruleId;
            //
            createRuleResponse = createRuleRequest(productKey, ENV_NAME + "云对讲在线状态回调", "统一创建", "deviceName,status,productKey,time", "+", 2);
            ruleId = createRuleResponse.getBody().getRuleId();
            createRuleActionRequest(ruleId, makeConfiguration(MNS_REGION_NAME, MNS_UID, TOPIC_ONLINE_CALLBACK));
            startRuleRequest(ruleId);
            //
            createRuleResponse = createRuleRequest(productKey, ENV_NAME + "云对讲开门状态上报", "统一创建", "deviceName() as deviceName,*", "+/user/deviceState", 1);
            ruleId = createRuleResponse.getBody().getRuleId();
            createRuleActionRequest(ruleId, makeConfiguration(MNS_REGION_NAME, MNS_UID, TOPIC_ALL));
            startRuleRequest(ruleId);
        }
    }

    public static void ypb() {
        CreateProductResponse response = createProduct(ENV_NAME + "云平板", "统一创建", 0, 1);
        if (response != null && response.getBody().getProductKey() != null) {
            String productKey = response.getBody().getProductKey();
            //
            createProductTopic(productKey, "cmd", "SUB");
            //
            CreateRuleResponse createRuleResponse;
            Long ruleId;
            //
            createRuleResponse = createRuleRequest(productKey, ENV_NAME + "云平板在线状态回调", "统一创建", "deviceName,status,productKey,time", "+", 2);
            ruleId = createRuleResponse.getBody().getRuleId();
            createRuleActionRequest(ruleId, makeConfiguration(MNS_REGION_NAME, MNS_UID, TOPIC_ONLINE_CALLBACK));
            startRuleRequest(ruleId);
        }
    }

    public static void yqk() {
        CreateProductResponse response = createProduct(ENV_NAME + "云群控", "统一创建", 0, 1);
        if (response != null && response.getBody().getProductKey() != null) {
            String productKey = response.getBody().getProductKey();
            //
            createProductTopic(productKey, "cmd", "SUB");
            createProductTopic(productKey, "notifyMessage", "PUB");
            //
            CreateRuleResponse createRuleResponse;
            Long ruleId;
            //
            createRuleResponse = createRuleRequest(productKey, ENV_NAME + "云群控在线状态回调", "统一创建", "deviceName,status,productKey,time", "+", 2);
            ruleId = createRuleResponse.getBody().getRuleId();
            createRuleActionRequest(ruleId, makeConfiguration(MNS_REGION_NAME, MNS_UID, TOPIC_ONLINE_CALLBACK));
            startRuleRequest(ruleId);
            //
            createRuleResponse = createRuleRequest(productKey, ENV_NAME + "云群控呼梯结果上报", "统一创建", "deviceName() as deviceName,*", "+/user/notifyMessage", 1);
            ruleId = createRuleResponse.getBody().getRuleId();
            createRuleActionRequest(ruleId, makeConfiguration(MNS_REGION_NAME, MNS_UID, TOPIC_ALL));
            startRuleRequest(ruleId);
        }
    }

    public static void yqk2() {
        String productKey = "a17mzOKXb83";
        CreateRuleResponse createRuleResponse;
        Long ruleId;
        //
        createRuleResponse = createRuleRequest(productKey, ENV_NAME + "云群控状态上报", "统一创建", "deviceName() as deviceName,*", "+/user/deviceState", 1);
        ruleId = createRuleResponse.getBody().getRuleId();
        createRuleActionRequest(ruleId, makeConfiguration(MNS_REGION_NAME, MNS_UID, TOPIC_ALL));
        startRuleRequest(ruleId);
    }

    public static void main(String[] args) {
        //ydt();
        //ymj();
        //ydj();
        //ypb();
        //yqk();
        yqk2();
    }

}
